package git.soulbgm.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Set;

/**
 * 缓存工具类
 *
 * @author SoulBGM
 * @date 2022/03/30 10:37
 */
@Service
public class CacheUtil {

    @Autowired
    private CacheManager cacheManager;

    public Cache getCache(String cacheName) {
        return cacheManager.getCache(cacheName);
    }

    public void put(String cacheName, String key, Object value) {
        getCache(cacheName).put(key, value);
    }

    public Object get(String cacheName, String key) {
        return getCache(cacheName).get(key);
    }

    public <T> T get(String cacheName, String key, Class<T> clazz) {
        return getCache(cacheName).get(key, clazz);
    }

    public Object get(String cacheName, String key, Object defaultValue) {
        Object value = get(cacheName, key);
        return value != null ? value : defaultValue;
    }

    public void remove(String cacheName, String key) {
        getCache(cacheName).evict(key);
    }

    public void removeAll(String cacheName) {
        getCache(cacheName).clear();
    }

    public void removeByKeys(String cacheName, Set<String> keys) {
        keys.forEach(k -> {
            remove(cacheName, k);
        });
    }

    public Collection<String> getCacheNames() {
        return cacheManager.getCacheNames();
    }
}
